class Schedule {
  constructor(limit) {
    this.taskQueue = []
    this.limit = limit
    this.curRun = 0
  }
  addTask(delay, order) {
    this.taskQueue.push(function () {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(order);
          resolve()
        }, delay)
      })
    })
  }
  start() {
    for (let i = 0; i < this.limit; i++) {
      // 取出最大运行任务数
      this.runTask()
    }
  }
  runTask() {
    if (!this.taskQueue || this.taskQueue.length <= 0 || this.curRun >= this.limit) return
    this.curRun++
    this.taskQueue.shift()().then(() => {
      this.curRun--
      this.runTask()
    })
  }
}

let s = new Schedule(2)
s.addTask(1000,'1')
s.addTask(500,'2')
s.addTask(300,'3')
s.addTask(400,'4')
s.start()